using System;
using System.Windows;
using DeSleeper.Client.Properties;
using DeSleeper.Client.WakeOnLanService;

namespace DeSleeper.Client.WakeUp
{
    public class HostNameWakeUpMethod : WakeUpMethod
    {
        public HostNameWakeUpMethod() {}
        public HostNameWakeUpMethod(TargetComputer target) : base(target) { }

        #region HostName Attached Property
        public static readonly DependencyProperty HostNameProperty =
            DependencyProperty.RegisterAttached("HostName", typeof (string), typeof (HostNameWakeUpMethod));

        public static string GetHostName(TargetComputer target)
        {
            return (string) target.GetValue(HostNameProperty);
        }

        public static void SetHostName(TargetComputer target, string value)
        {
            target.SetValue(HostNameProperty, value);
        }

        protected string HostName
        {
            get { return GetHostName(Target); }
            set { SetHostName(Target, value); }
        }
        #endregion

        /// <summary>
        /// A description of the target used to identify it to the user.
        /// </summary>
        public override string Description { get { return "Wake up using a known host name."; } }

        /// <summary>
        /// Identifier used to identify target to code.
        /// </summary>
        public override string Id { get { return "HostName"; } }

        /// <summary>
        /// Does the assigned target has enough and correct information to perform a wake
        /// up with this method?
        /// </summary>
        public override bool IsValid
        {
            get
            {
                if (!base.IsValid) return false;
                if (Uri.CheckHostName(HostName) == UriHostNameType.Unknown) return false;
                if (!Uri.IsWellFormedUriString(HostName, UriKind.RelativeOrAbsolute)) return false;
                return true;
            }
        }

        protected override void WakeUpCore(WakeUpServiceClient serviceClient)
        {
            if (!IsValid)
                throw new InvalidOperationException(Resources.ErrorInvalidHostName);

            serviceClient.WakeUpByHostName(HostName);
        }

        ///<summary>
        /// Creates a new instance to support cloning.
        ///</summary>
        protected override Freezable CreateInstanceCore()
        {
            return new HostNameWakeUpMethod(Target);
        }
    }
}